package com.demo.holder;

import java.sql.Connection;

/**
 * Created by hunter
 *
 * @Description 线程变量holder
 */
public class ThreadContextHolder {

    // 当前线程对应的事务id变量
    private static final ThreadLocal<String> TRANSACTION_CACHE = new ThreadLocal<>();
    // 当前线程对应的数据库连接变量
    private static final ThreadLocal<Connection> CONNECTION_CACHE = new ThreadLocal<>();
    // 当前线程对应的事务是否自动提交变量
    private static final ThreadLocal<Boolean> AUTO_COMMIT_CACHE = new ThreadLocal<>();

    /**
     * 设置当前线程事务id
     *
     * @param transactionId
     */
    public static void setTransactionId(String transactionId) {
        TRANSACTION_CACHE.set(transactionId);
    }

    /**
     * 获取当前线程事务id
     *
     * @return
     */
    public static String getTransactionId() {
        return TRANSACTION_CACHE.get();
    }

    /**
     * 移除当前线程事务id
     */
    public static void removeTransactionId() {
        TRANSACTION_CACHE.remove();
    }

    /**
     * 设置当前线程数据库连接
     *
     * @param connection
     */
    public static void setConnection(Connection connection) {
        CONNECTION_CACHE.set(connection);
    }

    /**
     * 获取当前线程数据库连接
     */
    public static Connection getConnection() {
        return CONNECTION_CACHE.get();
    }

    /**
     * 移除当前线程数据库连接
     */
    public static void removeConnection() {
        CONNECTION_CACHE.remove();
    }

    /**
     * 设置当前事务是否自动提交
     *
     * @param autoCommit
     */
    public static void setAutoCommit(boolean autoCommit) {
        AUTO_COMMIT_CACHE.set(autoCommit);
    }

    /**
     * 获取当前事务是否自动提交
     */
    public static boolean getAutoCommit() {
        return AUTO_COMMIT_CACHE.get();
    }

    /**
     * 移除当前事务是否自动提交
     */
    public static void removeAutoCommit() {
        AUTO_COMMIT_CACHE.remove();
    }
}
